package com.zzti.sys.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.wxpay.sdk.WXPayUtil;
import com.zzti.pay.utils.IPUtils;
import com.zzti.sys.service.WeChatPayService;

@RestController
public class WeChatController {
	@Autowired
	WeChatPayService weChatPayService;

	// h5调起微信支付
	public String toPay(HttpServletRequest request, @RequestBody Map<String, Object> map) {
		String IP = IPUtils.getIpAddress(request); // 请求的ip地址
		String body = (String) map.get("body"); // 订单信息
		String outTradeNo = (String) map.get("outTradeNo"); // 订单号
		String totalFee = (String) map.get("totalFee"); // 订单总金额 单位分
		return weChatPayService.topay(outTradeNo, totalFee, body, IP);
	}

	// 微信回调接口
	public String callBack(HttpServletRequest request) {
		System.out.println("微信支付回调");
		InputStream inStream;
		try {
			inStream = request.getInputStream();

			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			String resultXml = new String(outSteam.toByteArray(), "utf-8");
			Map<String, String> params = WXPayUtil.xmlToMap(resultXml);
			outSteam.close();
			inStream.close();
			return weChatPayService.notify(params);
		} catch (IOException e) {
			// 记录日志
			e.printStackTrace();
		} catch (Exception e) {
			// 记录日志
			e.printStackTrace();
		}
		return null;
	}

}
